package com;

import java.io.IOException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ConcurrentModificationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;


@SuppressWarnings("serial")
public class BidServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		String current = "";
		java.util.Date d1,d2;
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		java.util.Date currentDate = new java.util.Date();	
		current = df.format(currentDate);
		
	
		String msg = "";
		
		String itemID = req.getParameter("itemID");
		String username = req.getParameter("username");
		double currentBid = Double.parseDouble(req.getParameter("currentBid"));
		String endTime="";
		String bid = req.getParameter("bid");
		double userBid;
		
		Entity e;
		
		try {
			e = ds.get(KeyFactory.createKey("Auction", Integer.parseInt(itemID)));
			endTime = (String) e.getProperty("END");
		} catch (EntityNotFoundException ex) {
		}

		try {
			d1 = df.parse(endTime);
			d2 = df.parse(current);
			
			if(d2.after(d1)){
				//auction has expired
				msg = "Error. Auction is expired.";
				req.setAttribute("msg", msg);

				
				System.out.println(msg);

				req.getRequestDispatcher("error.jsp").forward(req, resp);
			}else if(bid == ""){
				//auction has expired
				msg = "Error. Please enter a value for bid.";
				req.setAttribute("msg", msg);

				
				System.out.println(msg);

				req.getRequestDispatcher("error.jsp").forward(req, resp);
				
			}else if(!isDouble(bid)){

				//invalid bid
				msg = "Error. Invalid value for bid.";
				req.setAttribute("msg", msg);

				
				System.out.println(msg);

				req.getRequestDispatcher("error.jsp").forward(req, resp);
			}else{
				userBid = Math.round(Double.parseDouble(bid)*100)/100.0;
				if(userBid<= currentBid){
					//invalid bid
					msg = "Error. Bid is too low.";
					req.setAttribute("msg", msg);

					
					System.out.println(msg);

					req.getRequestDispatcher("error.jsp").forward(req, resp);
				}else{

					for (int j = 0; j < 10; j++) {
						Transaction tx = ds.beginTransaction();
						try {
							Entity b = new Entity("Bid");
							b.setProperty("ITEMID", itemID);
							b.setProperty("BIDDER", username);
							b.setProperty("OFFER", userBid);
							b.setProperty("TIME", current);		
							//Blackboard style
							ds.put(tx, b);
							tx.commit();
							break;
							
							
						} catch (ConcurrentModificationException ed) {
							// continue
						} finally {
							if (tx.isActive())
								tx.rollback();
						}
					}
					req.setAttribute("username", username);
					req.getRequestDispatcher("buyerIndex.jsp").forward(req, resp);
				}

			}
			
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
					
		
	}
	
	public static boolean isDouble (String str){
		try{
			double d = Double.parseDouble(str);
		}catch(NumberFormatException e){
			return false;
		}
		return true;
	}
}